package com.gitee.itembucket.core.bucket

import com.gitee.itembucket.ItemBucket
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta
import java.util.Collections

open class Bucket {

    val items = Collections.synchronizedList(mutableListOf<Item>())

    fun checkItem(itemStack: ItemStack): Int {
        return items.indexOfFirst { it.stack.isSimilar(itemStack) }
    }

    fun getItem(index: Int): Item? {
        return items.getOrNull(index)
    }

    fun checkItem(item: Item): Int {
        return items.indexOfFirst { it == item || (!it.isFull && it.stack.isSimilar(item.stack)) }
    }

    fun addItem(item: Item): Int {
        items += item
        return items.size - 1
    }

    class Clone : Bucket()

    class Item(
        var id: Long,
        val stack: ItemStack,
        private var amount: Long
    ) {

        var changed = true

        fun get(amount: Long): Long {
            return if (this.amount >= amount) {
                this.amount -= amount
                changed = true
                amount
            } else {
                val takeAmount = this.amount
                this.amount = 0
                this.changed = true
                takeAmount
            }
        }

        /**
         * 空缺
         */
        val emptySize: Long
            get() = ItemBucket.stackSize - this.amount

        val isFull: Boolean
            get() = emptySize == 0L

        fun getAmount(): Long {
            return this.amount
        }

        fun put(amount: Int) {
            this.put(amount.toLong())
        }

        fun put(amount: Long) {
            this.amount += amount
            this.changed = true
        }

        init {
            stack.amount = 1
        }

    }

}